/*
 * @Author: 蔡霸霸
 * @Date: 2020-05-12 10:13:06
 * @LastEditors: 蔡霸霸
 * @LastEditTime: 2020-06-17 16:41:16
 * @FilePath: \Nuxt_music\plugins\axios.js
 */

// import axios from 'axios'
import { message } from 'ant-design-vue'
import axios from 'axios'
import { getToken, getUid } from '@/utils/auth'

export default ({ $axios, redirect, store, error }) => {
  if (store.state.token && store.state.uid && !store.state.name) {
    //* 状态保持
    store.dispatch('getInfo')
  }
  $axios.onRequest((config) => {
    // todo-- 这里可以做请求拦截  添加请求头
    let token = getToken()
    let uid = getUid()

    try {
      if (!token && axios.defaults.cookies.MUSIC_U) {
        token = axios.defaults.cookies.MUSIC_U
      }
      if (!uid && axios.defaults.cookies.uid) {
        uid = axios.defaults.cookies.uid
      }
    } catch (err) {}

    if (!store.state.token || !store.state.uid) {
      store.commit('SET_TOKEN', token)
      store.commit('SET_UID', uid)
    }
    return config
  })

  $axios.onResponse((response) => {
    // todo-- 这里可以做返回拦截 拦截跳转
    const res = response
    if (res.data.code !== 200) {
      message.error({
        content: res.data.message,
        duration: 2 // todo--  秒为单位
      })
      return error({ statusCode: res.data.code, message: res.data.message })
    } else {
      return res
    }
  })
  $axios.onError((error) => {
    message.error({
      content: error.response.data.message,
      duration: 2 // todo--  秒为单位
    })
    return error
    // todo-- 这里可以做错误拦截  指向404
  })
}
